<template>
    <a-drawer popup-container="#wrap" width="100%" :footer="false" :visible="show" :ok-loading="form.loading"
        @cancel="show = false">
        <template #title>
            {{ $t('components.playback.60zelfaja300') }}
        </template>
        <div class="box">
            <div class="form">
                <div class="search-title">{{ $t('components.playback.60zekq5nwb82') }}</div>
                <div class="search-demo">
                    <a-form ref="formRef" layout="inline" :model="form" @submit="getData">
                        <div class="inputGroup">
                            <a-form-item field="value" :label="$t('spectRecord.spectRecord.60zelpzsfbo0')">
                                <a-range-picker />
                            </a-form-item>
                            <a-space>
                                <a-button @click="getData" type="primary" html-type="submit">
                                    <template #icon>
                                        <icon-search />
                                    </template>
                                    {{ $t('data.data.60zec2kc0ns0') }}
                                </a-button>
                                <a-button type="outline" @click="formRef?.resetFields()">
                                    <template #icon>
                                        <icon-refresh />
                                    </template>
                                    {{ $t('data.data.60zec2kc1x00') }}
                                </a-button>
                            </a-space>
                        </div>
                    </a-form>
                </div>
            </div>
            <div class="info" v-if="form.detail?.uavBasic?.id">
                <div class="info-title">{{ $t('components.playback.60zekq5nwb81') }}</div>
                <div class="info-demo">
                    <div>
                        <div class="name">{{ $t('components.playback.60zekq5nwb84') }}：</div>
                        <div>{{ form.detail?.uavBasic?.id }}</div>
                    </div>
                    <div>
                        <div class="name">{{ $t('components.playback.60zekq5nwb80') }}：</div>
                        <div>
                            <span v-if="form.detail?.uavBasic?.uavType === 1">{{ $t('components.spect.60zduu0v7gc0') }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 2">{{ $t('components.spect.60zduu0v7wo0')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 3">{{ $t('components.spect.60zduu0v87o0')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 4">{{ $t('components.spect.60zduu0v8j00')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 5">{{ $t('components.spect.60zduu0v8us0')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 6">{{ $t('components.spect.60zduu0v91w0')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 7">{{ $t('components.spect.60zduu0v9r00')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 8">{{ $t('components.spect.60zduu0v9z80')
                                }}</span>
                            <span v-else-if="form.detail?.uavBasic?.uavType === 9">{{ $t('components.spect.60zduu0va740')
                                }}</span>
                            <span v-else>{{ $t('components.spect.60zduu0vadk0') }}</span>
                        </div>
                    </div>
                    <div>
                        <div class="name">{{ $t('components.spect.60zduu0v1x47') }}：</div>
                        <div>{{ form.detail?.rssi }}</div>
                    </div>
                    <div>
                        <div class="name">{{ $t('components.spect.60zdu10vax47') }}：</div>
                        <div>{{ form.detail?.uavLocation?.height }}m</div>
                    </div>
                    <div>
                        <div class="name">{{ $t('components.spect.60zdu00vax47') }}：</div>
                        <div>{{ form.detail?.uavLocation?.speedV }}m/s</div>
                    </div>
                    <div>
                        <div class="name">{{ $t('components.spect.60zdu00vax87') }}：</div>
                        <div>{{ form.detail?.uavLocation?.speedH }}m/s</div>
                    </div>
                    <div>
                        <div class="name">{{ $t('components.spect.60zdu00vax80') }}：</div>
                        <div>{{
                            Number(form.detail?.uavLocation.lon.toFixed(4)) }},{{
                                Number(form.detail?.uavLocation.lat.toFixed(4)) }}</div>
                    </div>
                </div>
            </div>
            <div class="playback">
                <div class="track" id="track"></div>
            </div>
            <div class="footer">
                <div></div>
                <div>
                    <a-space>
                        <div style="width: 50px;display: flex;justify-content: center;">
                            <a-button shape="circle" type="primary" @click="start" v-if="play != 1">
                                <template #icon>
                                    <icon-play-arrow />
                                </template>
                            </a-button>
                            <a-button shape="circle" type="primary" @click="stop" v-if="play == 1">
                                <template #icon>
                                    <icon-pause />
                                </template>
                            </a-button>
                        </div>
                        <!-- //0->未开始  1->行驶中  2->暂停 -->
                        <!-- <div style="width: 50px;display: flex;justify-content: center;">
                            <a-button shape="circle" type="primary" @click="start" v-if="play == 0">
                                <template #icon>
                                    <icon-play-arrow />
                                </template>
                            </a-button>
                            <a-button shape="circle" type="primary" @click="stop" v-if="play == 1">
                                <template #icon>
                                    <icon-pause />
                                </template>
                            </a-button>
                            <a-button shape="circle" type="primary" @click="resume" v-if="play == 2">
                                <template #icon>
                                    <icon-play-arrow />
                                </template>
                            </a-button>
                        </div> -->
                        <!--进度条-->
                        <!-- <div style="padding: 0 10px;display: flex;align-items: center;gap: 10px;">
                            <a-slider @change="change" style="width: 300px;margin-right: 30px;" :max="list?.length"
                                v-model="slider">
                                <template #mark="{ label, point }">
                                    <template v-if="point === list?.length">
                                        <strong>{{ label }}</strong>
                                    </template>
                                    <template v-else>{{ label }}</template>
                                </template>
                            </a-slider>
                            <span style="width: 50px;text-align: center;">{{ (slider / (list?.length - 1) *
                                100).toFixed(2)
                                }}%</span>
                            <span>/</span>
                            <span style="width: 50px;text-align: center;">100.00%</span>
                        </div> -->
                        <div style="padding: 0 10px;display: flex;align-items: center;gap: 10px;">
                            <a-slider @change="change" style="width: 300px;margin-right: 30px;" :max="list?.length"
                                v-model="slider">
                                <template #mark="{ label, point }">
                                    <template v-if="point === list?.length">
                                        <strong>{{ label }}</strong>
                                    </template>
                                    <template v-else>{{ label }}</template>
                                </template>
                            </a-slider>
                            <span style="width: 50px;text-align: center;">{{ (slider / (list?.length - 1) *
                                100).toFixed(2)
                                }}%</span>
                            <span>/</span>
                            <span style="width: 50px;text-align: center;">100.00%</span>
                        </div>
                        <!-- 动画控制进度条 -->
                        <!-- <div class="progressDiv_speedDiv">
                            <el-select v-model="speedCount" @change="speedCountChange($event)" placeholder="倍速选择"
                                :clearable="false">
                                <el-option v-for="(item, index) in speedCountArr" :label="item.name" :value="item.value"
                                    :key="index" />
                            </el-select>
                        </div> -->
                        <!-- <div class="progressDiv_timeDiv">
                            {{ times }}
                        </div> -->
                    </a-space>
                </div>
                <div style="display: flex;justify-content: end;">
                    <a-button type="primary" @click="show = false">{{ $t('components.playback.60zelfajbcg0')
                        }}</a-button>
                </div>
            </div>
        </div>
    </a-drawer>
</template>

<script lang='ts' setup>
import { Scene, PointLayer } from '@antv/l7';
import { GaodeMap } from '@antv/l7-maps';
import { apiSpectTrack } from '@/api/index'
import dayjs from 'dayjs'
const formRef = ref()
const show = defineModel('show', { default: false })
const detail: any = defineModel('data', { default: {} })
const emit = defineEmits(['refresh'])
const local = useLocal()
const form = reactive({
    loading: false,
    mounted: false,
    data: {
        // startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
        // endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    } as any,
    detail: {} as any,
    points: [] as any,
    uavOperatorInfo: {} as any
})
// const speedCountArr = reactive([
//     {
//         name: '0.5X',
//         value: 0.5,
//     },
//     {
//         name: '0.75X',
//         value: 0.75,
//     },
//     {
//         name: '1.0',
//         value: 1.0,
//     },
//     {
//         name: '1.25X',
//         value: 1.25,
//     },
//     {
//         name: '1.5X',
//         value: 1.5,
//     },
//     {
//         name: '1.75X',
//         value: 1.75,
//     },
//     {
//         name: '2.0X',
//         value: 2.0,
//     },
//     {
//         name: '2.5X',
//         value: 2.5,
//     },
//     {
//         name: '3.0X',
//         value: 3.0,
//     },
// ])
const getData = async () => {
    // let arr = [[121.4705, 31.3967]];
    // for (let i = 1; i < 50; i++) {
    //     arr = [...arr, useGenerateRandomLatLonWithinDistance(arr[arr.length - 1], 20)]
    // }
    form.loading = true
    const { code, data } = await apiSpectTrack({
        ...form.data,
        deviceId: form.data.uavBasic.id,
        // startTime: Number(dayjs().subtract(7, 'day').format('X')),
        startTime: Number(dayjs().subtract(7, 'day').format('X')),
        endTime: Number(dayjs().format('X')),
    })
    form.loading = false
    if (code != 200) return
    form.detail = data
    form.points = data.points
    form.uavOperatorInfo = data.uavOperatorInfo
    // console.log(form.detail.uavBasic.id)
    // form.points = arr
    nextTick(() => {
        init()
    })
}
const play = ref(0)
// const isSpeedCountChange = ref(false)
// const isSliderValChange = ref(false) // 进度条改变
// const reDrawPolyline = ref(0)//倍数变化之后，需要从新绘制线
const slider = ref(0)
const scene = ref()
const marker = ref()
const speed = computed(() => 300)
const list = computed(() => form.points?.filter((item: any) => !!item[0]))
const operatorPointLayer = ref()
const passedPolyline = ref()
//无人机操作人员定位操作
const createOperatorPointLayer = () => {
    operatorPointLayer.value = new PointLayer({
        zIndex: 2,
    }).source(
        [
            {
                lng: form.uavOperatorInfo.lon,
                lat: form.uavOperatorInfo.lat
            }
        ]
        , {
            parser: {
                type: 'json',
                x: 'lng',
                y: 'lat',
                // zoomOffset: 1,
            },
        })
        .shape('01')
        .size(20);
    scene.value.addLayer(operatorPointLayer.value)
}
const init = () => {
    destroy()
    scene.value = new Scene({
        id: 'track',
        map: new GaodeMap({
            style: 'normal',
            token: local.mapKey.aMap,
            zoom: 2,
            plugin: ['AMap.MoveAnimation', 'AMap.Polyline'],
        }),
        logoVisible: false,
    });
    scene.value.addImage(
        '01',
        '/pilot.svg',
    );
    scene.value?.on('loaded', () => {
        createOperatorPointLayer();
        (window as any).AMap.plugin(['AMap.MoveAnimation', 'AMap.Polyline', 'AMap.Size'], () => {
            // @ts-ignore
            let icon = new AMap.Icon({
                // @ts-ignore
                size: new AMap.Size(40, 40),
                image: '/spect.svg',
                // @ts-ignore
                imageSize: new AMap.Size(40, 40),
            });
            // @ts-ignore
            marker.value = new AMap.Marker({
                map: scene.value.map,
                position: list.value[0],
                icon,
            });
            // 绘制轨迹
            // @ts-ignore
            let polyline = new AMap.Polyline({
                // @ts-ignore
                map: scene.value.map,
                path: list.value,
                showDir: true,
                strokeColor: "#28F",  //线颜色
                strokeWeight: 6,      //线宽
            });
            // @ts-ignore
            passedPolyline.value = new AMap.Polyline({
                // @ts-ignore
                map: scene.value.map,
                strokeColor: "#AF5",  //线颜色
                strokeWeight: 6,      //线宽
            });


            marker.value.on('moving', function (e: any) {
                // console.log(e.passedPath.length)
                passedPolyline.value.setPath(e.passedPath);
                slider.value = e.passedPath?.length - 1
                scene.value.map.setCenter(e.target.getPosition(), true)
            });

            scene.value.map.setFitView();
            play.value = 0
        })
    })
}

// let timer: any = null
// const start = () => {
//     play.value = 1
//     timer = setInterval(() => {
//         slider.value++
//         marker.value.moveTo(list.value[slider.value])
//         scene.value.setCenter(list.value[slider.value], true)
//         if (slider.value == (list.value?.length - 1)) {
//             slider.value = 0
//             return stop()
//         }
//     }, speed.value)
// }
// const stop = () => {
//     clearInterval(timer)
//     timer = null
//     play.value = 0
// }
const start = () => {
    if (play.value > 0 && play.value == 0) { //未播放的情况下，直接从指定位置开始播放
        marker.value.moveAlong(list.value, {
            // 每一段的时长
            duration: speed.value,//可根据实际采集时间间隔设置
            // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
            autoRotation: false,
        });
    } else {
        marker.value.resumeMove()
    }
    play.value = 1
}
const stop = () => {
    marker.value.pauseMove();
    play.value = 2
}
// const resume = () => {
//     if ((play.value == 2 && isSpeedCountChange.value) || (play.value == 2 && isSliderValChange.value)) {
//           isSpeedCountChange.value = false;
//           isSliderValChange.value = false;
//           reDrawPolyline(2); //倍数变化之后，需要从新绘制线
//         }
//         marker.value.resumeMove()
//         play.value = 1; //0->未开始  1->行驶中  2->暂停
// }
//倍速选择
// const speedCountChange= (e) =>  {
//     // carPalyStayus //0->未开始  1->行驶中  2->暂停
//     // 如果正在行驶中点击倍数
//     if (play.value == 1) {
//         marker.value.resumeMove()
//         reDrawPolyline(1); //倍数变化之后，需要从新绘制线
//     } else if (play.value == 2) {
//         isSpeedCountChange.value = true;
//     }
// }
// 进度条
const change = debounce((value: any) => {
    let vehicleLocation = list.value[value - 1]
    // @ts-ignore
    marker.value.setPosition(new AMap.LngLat(vehicleLocation[0], vehicleLocation[1]))
    start()
    // play.value = 1
    // if(play.value)
}, 300)
// const change = () => {
//     //手动拖动进度条过程中触发：移动车辆，定位车辆回放位置
//         //计算拖动进度条后车辆对应轨迹新的索引值
//         var getIndex = Math.round(that.carLineArr.length * that.sliderVal / 100);
//         var currentIndex = 0
//         if (getIndex > 0) {
//            currentIndex = getIndex - 1;
//         }
//         var vehicleLocation = list.value[currentIndex];
//         marker.value.setPosition(new AMap.LngLat(vehicleLocation[0], vehicleLocation[1]));
//         if (currentIndex == 0) {
//           that.progval = 1;  //处理重新绘制线路时 that.progval-1 找不到值报错
//         } else {
//           that.progval = currentIndex;
//         }
//         that.progvalLength = that.progval;
//         // carPalyStayus //0->未开始  1->行驶中  2->暂停
//         if (play.value == 0) {
//         } else if (play.value == 1) {
//           marker.value.resumeMove() // 先暂停车
//           that.reDrawPolyline(1); //倍数变化之后，需要从新绘制线
//         } else if (play.value == 2) {
//           isSliderValChange.value = true;
//         }
// }
useWatch(show, (val: boolean) => {
    if (val) {
        form.data = {
            ...detail.value
        }
        getData()
    } else {
        destroy()

    }
})
const destroy = () => {
    scene.value && scene.value?.destroy()
    scene.value = null;
    slider.value = 0
    setTimeout(() => {
        form.mounted = false
        nextTick(() => {
            form.mounted = true
        })
    }, 500);
}
onBeforeUnmount(() => {
    destroy()
})
</script>
<style lang="less" scoped>
.box {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .form {
        position: absolute;
        top: 0;
        left: 0;
        width: 400px;
        // height: 500px;
        background-color: #fff;
        border: 1px solid #e0dfdf;
        border-radius: 8px;
        z-index: 999;

        >.search-title {
            font-size: 16px;
            margin: 20px 20px 10px 20px;
        }

        >.search-demo {
            width: 100%;
            height: calc(18% - 16px);
            background-color: var(--data-bg-color);
            border: 1px solid var(--data-border-color);
            margin-bottom: 16px;
            border-radius: 5px;
            display: flex;
            align-items: center;
            padding: 0 20px;

            .inputGroup {
                width: 100%;
                display: flex;
                flex-direction: column;
            }

            :deep(.arco-space-align-center) {
                margin-right: 20px;
            }

            :deep(.arco-select-view-single) {
                background-color: var(--data-input-color) !important;
                border: 1px solid var(--data-border-color);
                width: 65%;
            }

            :deep(.arco-form-layout-inline .arco-form-item) {
                width: 100%;
                margin-bottom: 12px;
            }

            :deep(.arco-picker, .arco-picker) {
                background-color: var(--data-input-color) !important;
                border: 1px solid var(--data-border-color);
                // width: 280px;
            }

            :deep(.arco-feedback-icon) {
                display: none;
            }

            :deep(.arco-btn-primary) {
                background-color: var(--botton-bg-color);
            }

            :deep(.arco-btn-outline) {
                color: var(--botton-bg-color);
                border: 1px solid var(--botton-bg-color);
            }
        }
    }

    .info {
        position: absolute;
        top: 0;
        right: 0;
        width: 350px;
        // height: 500px;
        background-color: #fff;
        border: 1px solid #e0dfdf;
        border-radius: 8px;
        z-index: 999;
        font-size: 14px;

        >.info-title {
            font-size: 16px;
            margin: 20px 20px 10px 20px;
        }

        >.info-demo {
            margin: 0 20px 10px 20px;

            >div {
                margin-bottom: 10px;
                display: flex;

                >.name {
                    width: 120px;
                    color: #666;
                }
            }
        }
    }

    .playback {
        flex: 1;

        .track {
            position: relative;
            width: 100%;
            height: 100%;
            border-radius: 5px;
            overflow: hidden;
        }
    }

    .footer {
        width: 100%;
        display: flex;
        justify-content: space-between;
        padding-top: 16px;

        >div {
            &:first-of-type {
                width: 20%;
            }

            &:nth-of-type(2) {
                width: 80%;
                display: flex;
                justify-content: center;
            }

            &:last-of-type {
                width: 20%;
            }
        }
    }
}
</style>